# -*- coding: utf-8 -*-
"""
Module Description:
Date: 2018/11/09
Auchor: Likejian
"""
import json
from collections import defaultdict

from pyshare.const.lang_enum import LangEnum, LangMapping
from pyshare.dal.gameconfig.query import getProfile
from pyshare.const.lang.tips_info import TipsInfo
from common.server_config import is_debug


def translater(tip_key, lang=None):
    """
    多语言翻译
    usage:
        # 以双下划线表示翻译函数
        from pyshare.const.lang.translate import translater as __
        __(TipsInfo.xxxxx)
        # 或者
        __(TipsInfo.xxxxx).format(xxx)

    :param tip_key: 被翻译的词
    :param lang: 翻译的语言
    :return: str
    """

    defaut = LangEnum.Simplified
    from pyshare.core.context import action_context_storage

    if not lang:
        if action_context_storage.ctx is not None:
            lang = action_context_storage.ctx.lang
        else:
            lang = LangEnum.Simplified

    field = LangMapping.mapping[defaut] if lang not in LangMapping.mapping.keys() else LangMapping.mapping[lang]

    # # 对应的数据库字段
    # mapping = {
    #     'zh-cn': 'Simplified',
    #     'zh-tw': 'Traditional',
    #     'en': 'English',
    #     'ko-kr': 'Korean',
    #     'ja-jp': 'Japanese'
    # }
    tc_translate = getProfile('TcTipsTranslate', TipKey=tip_key)

    if tc_translate is None:
        tc_translate = getProfile('TcTipsTranslate', TipKey=TipsInfo.GlobalKeys.defaultErrorInfo)

    translate_info = getattr(tc_translate, field)
    if is_debug and translate_info is None:
        translate_info = "语言版本({lang})的提示文本({key})还没有翻译文本~".format(lang=lang, key=tip_key)
    return translate_info


def translate_config_to_dict(config):
    """
     >>>	def(config_object):
     ... 	    return config_dict
    """

    config_dict = defaultdict(str)

    if not config:
        return config_dict

    for k, v in LangMapping.mapping.items():
        lang = getattr(config, v)
        if lang:
            try:
                lang = json.loads(lang)
            except:
                pass
            config_dict[k] = lang
    return config_dict


# 推送语言兼容
def translate_device_push(content):
    """
     >>>	def(defaultdict):
     ... 	    return defaultdict
    """

    config_dict = defaultdict(str)
    for k, v in content.items():
        if k in LangMapping.device_push_mapping:
            config_dict[LangMapping.device_push_mapping[k]] = v

    return config_dict
